package com.example.fresh_fruit.service.Impl;

import com.example.fresh_fruit.entity.Commodity;
import com.example.fresh_fruit.entity.ShoppingCat;
import com.example.fresh_fruit.mapper.CommodityMapper;
import com.example.fresh_fruit.mapper.ShoppingCatMapper;
import com.example.fresh_fruit.service.ShoppingCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author :飞天の鱼
 * @date : 2022/8/24 14:39
 */
@Service
public class ShoppingCatServiceImpl implements ShoppingCatService {
    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private ShoppingCatMapper shoppingCatMapper;

    @Override
    public ShoppingCat selectShoppingCom(Integer id) {
        return shoppingCatMapper.selectShoppingCom(id);
    }

    @Override
    public int insertShoppingCom(Commodity commodity) {
        long commodityId = commodity.getId();
        //根据加入购物车商品的id,比较要加入的数量与商品的数量的值
        Commodity commodityMapperById = commodityMapper.findById(Math.toIntExact(commodityId));
        //要加入购物车的数量
        double commodityNumber = commodity.getNumber();
//        商品的数量
        double commodityMapperByIdNumber = commodityMapperById.getNumber();
        double result = commodityMapperByIdNumber - commodityNumber;
        //result<0,没有那么多的数量可售
        if (result < 0) {
            return 1;
        }
        ShoppingCat selectShoppingCom = selectShoppingCom(Math.toIntExact(commodityId));
        //先查询购物车中是否有已下了的商品订单，如果没有，则可以直接加入到购物车中
        if (selectShoppingCom != null) {
            //如果购物车中已有下了的商品订单，先将其删除
            shoppingCatMapper.deleteShoppingCom(Math.toIntExact(commodityId));
            //原先购物车中已经存在了当前要加的商品，则在购物车商品数量的情况下加上后加的商品
            double commodityNumber1 = selectShoppingCom.getCommodityNumber();
            double sumCom = commodityNumber1 + commodityNumber;
            commodity.setNumber(sumCom);
        }
        int insertShoppingCom = shoppingCatMapper.insertShoppingCom(commodity);
        //插入购物车失败
        if (insertShoppingCom != 1) {
            return 2;
        }
        return 0;
    }

    @Override
    public int deleteShoppingCom(Integer id) {
        return shoppingCatMapper.deleteShoppingCom(id);
    }
}
